#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
#include <vector>
#include<cstring>
#include<string>

using namespace std;

const int num = 5;

int* p=nullptr; //指向线程独立栈的局部对象
__thread pthread_t g_tid=10;      //线程局部存储

class ThreadData
{
public:
    ThreadData(const string &threadname)
        : _threadname(threadname)
    {
    }

public:
    string _threadname; // 线程名
};

string toHex(pthread_t tid)
{
    char buf[128];
    snprintf(buf,sizeof(buf),"%p",tid);

    return buf;
}

void *routine(void *args)
{
    pthread_detach(pthread_self()); //线程分离
    int value=0;
    ThreadData *td = static_cast<ThreadData *>(args);
    if(td->_threadname=="thread 2") p=&value;
    int cnt=0;
    while (true)
    {
        // printf("name: %s, tid: %d\n",td->_threadname,td->_tid);
        cout << "name: " << td->_threadname << ", tid: " << toHex(pthread_self()) <<", value: "<<value<<", "<<"&value: "<<&value<<"g_tid: "<<g_tid++<<", &g_tid:"\
        <<&g_tid<<", pid: "<<getpid()<<endl;

        cnt++;
        value++;
        sleep(1);
 
        if(cnt>=10) break;
    }
    // printf("thread 2 , value: %d, &value :%p\n",*p,p);
    cout<<td->_threadname<<": quit..."<<endl;
    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tdv;
    for (int i = 1; i <= num; i++)
    {
        pthread_t tid;
        string tdname = "thread "+to_string(i);
        ThreadData *td = new ThreadData(tdname);

        pthread_create(&tid, nullptr, routine, td);
        tdv.push_back(tid);

        usleep(1000);

    }

    // cout<<"thread 2: "<<"value= "<<*p<<", &value: "<<p<<endl;
    printf("main thread get a mag:  value: %d, &value :%p\n",*p,p);     //从主线程获取其他线程独立栈中的变量

    sleep(100); //观察线程分离的情况

    // for (int i = 0; i < tdv.size(); i++)
    // {
    //     int n=pthread_join(tdv[i], nullptr);
    //     cout<<"n = "<<n<<", who: "<<toHex(tdv[i])<<", "<<"why: "<<strerror(n)<<endl;
    // }

    cout<<"main thread quit..."<<endl;
    return 0;
}